package com.sam.demo.service;

import com.sam.demo.config.DataSourceContextHolder;
import com.sam.demo.config.DynamicDataSourceRouter;
import com.sam.demo.config.JpaDataSourceConfigCommon;
import com.sam.demo.entity.UserEntity;
import com.sam.demo.repository.UserEntityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class UserService {
    @Autowired
    private UserEntityRepository userEntityRepository;
    @Autowired
    private DynamicDataSourceRouter routingDataSource;

    @Transactional
    public UserEntity saveUser(String name) throws Exception{
        UserEntity user = new UserEntity();
        user.setName(name + "33");
        userEntityRepository.save(user);

//        DataSourceContextHolder.setDataSource(JpaDataSourceConfigCommon.PRIMARY_DATASOURCE_KEY);
//        routingDataSource.determineTargetDataSource();
//        UserEntity user2 = new UserEntity();
//        user2.setName(name + "44");
//        userEntityRepository.save(user2);

        if(1==1){
            //throw new RuntimeException();
        }
        return user;
    }

    public UserEntity findUserById(Long id){
        return userEntityRepository.findOne(id);
    }
}
